﻿using Common.Configurations;
using Infrastructure.Persistence.Interceptors;
using Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Common.Extensions;
using Common.EfCore;
using Common.Services;
using Domain.Services;

namespace Infrastructure;

public static class DependencyInjection
{
    public static IServiceCollection AddDefaultInfrastructureServices(this IServiceCollection services,
       IConfiguration config)
    {
        #region 雪花ID
        SnowFlakeSettings snowFlakeSettings = config.GetSection(SnowFlakeSettings.Key).Get<SnowFlakeSettings>()!;
        services.AddSingleton<ISnowFlakeService>(new SnowFlakeService(snowFlakeSettings.WorkerId, snowFlakeSettings.DataCenterId));
        #endregion

        #region 数据库配置信息
        services.Configure<DatabaseSettings>(config.GetSection(DatabaseSettings.Key));
        services.AddScoped<ISaveChangesInterceptor, AuditableEntityInterceptor>();
        services.AddScoped<ISaveChangesInterceptor, DispatchDomainEventsInterceptor>();
        services.AddScoped<IDbCommandInterceptor, SqlExecutionInterceptor>();
        services.AddDbContext<ApplicationDbContext>((p, m) =>
        {
            var databaseSettings = p.GetRequiredService<IOptions<DatabaseSettings>>().Value;
            m.UseRemoveForeignKeyService(databaseSettings);
            m.AddInterceptors(p.GetServices<ISaveChangesInterceptor>());
            m.AddInterceptors(p.GetServices<IDbCommandInterceptor>());
            m.UseDatabase(databaseSettings.DBProvider, databaseSettings.ConnectionString);
        });
        services.AddScoped<IDbContextFactory<ApplicationDbContext>, ContextFactory<ApplicationDbContext>>();
        services.AddScoped<IApplicationDbContext>(provider =>
            provider.GetRequiredService<IDbContextFactory<ApplicationDbContext>>().CreateDbContext());
        #endregion

        return services;
    }
}
